"""基础Pipeline抽象类

定义PPG处理Pipeline的标准接口和基础功能

作者: PPG算法包开发团队
版本: 2.0.0
"""

from abc import ABC, abstractmethod
from typing import Dict, Any, Optional
import numpy as np
import logging

try:
    from .data_types import PPGSignal, PPGResults, HRVResults, QualityResults
    from ..config.pipeline_config import PipelineConfig
except ImportError:
    # 处理直接运行时的导入问题
    import sys
    from pathlib import Path
    sys.path.append(str(Path(__file__).parent.parent))
    from core.data_types import PPGSignal, PPGResults, HRVResults, QualityResults
    from config.pipeline_config import PipelineConfig

logger = logging.getLogger(__name__)


class BasePipeline(ABC):
    """PPG处理Pipeline基类
    
    定义所有Pipeline必须实现的接口方法
    """
    
    def __init__(self, config: PipelineConfig):
        """初始化Pipeline
        
        参数:
            config: Pipeline配置
        """
        self.config = config
        self.name = config.name
        self.sampling_rate = config.sampling_rate
        self._processing_info = {}
        
        # 验证配置
        if not config.validate():
            raise ValueError(f"Pipeline配置验证失败: {config.name}")
        
        logger.info(f"初始化Pipeline: {self.name}")
    
    @abstractmethod
    def process(self, signal: PPGSignal) -> PPGResults:
        """处理PPG信号
        
        参数:
            signal: 输入PPG信号
            
        返回:
            PPGResults: 处理结果
        """
        pass
    
    @abstractmethod
    def preprocess(self, signal_data: np.ndarray) -> Dict[str, np.ndarray]:
        """预处理步骤
        
        参数:
            signal_data: 原始信号数据
            
        返回:
            Dict: 包含各个预处理步骤结果的字典
        """
        pass
    
    @abstractmethod
    def detect_peaks(self, processed_signal: np.ndarray) -> tuple:
        """峰值检测步骤
        
        参数:
            processed_signal: 预处理后的信号
            
        返回:
            tuple: (peaks, properties) 峰值位置和属性
        """
        pass
    
    @abstractmethod
    def calculate_heart_rates(self, peaks: np.ndarray) -> Optional[np.ndarray]:
        """计算瞬时心率（抽象方法）
        
        由具体Pipeline实现算法逻辑。
        """
        pass
    
    @abstractmethod
    def calculate_hrv(self, peaks: np.ndarray) -> Optional[HRVResults]:
        """计算HRV指标（抽象方法）
        
        由具体Pipeline实现算法逻辑。
        """
        pass
    
    @abstractmethod
    def assess_quality(self, original_signal: np.ndarray, processed_signal: np.ndarray, 
                      peaks: np.ndarray) -> Optional[QualityResults]:
        """评估信号质量（抽象方法）
        
        由具体Pipeline实现算法逻辑。
        """
        pass
    
    def _log_processing_step(self, step_name: str, info: Dict[str, Any]):
        """记录处理步骤信息"""
        self._processing_info[step_name] = info
        if self.config.output_options.get("verbose", False):
            logger.info(f"{step_name}: {info}")
    
    def get_processing_info(self) -> Dict[str, Any]:
        """获取处理过程信息"""
        return self._processing_info.copy()